<?php
// 主页
namespace Admin\Controller;

use Think\Controller;
use Org\Net\UpYun;
use Org\Net\UploadFile;

class AjaxController extends CommonController {
	public function upload() {
		$dir = I ( 'get.site' );
		$dir = ($dir ? $dir : date ( 'Y' )) . '/';
		$name = I ( 'get.category' );
		$dir .= ($name ? $name : date ( 'm' )) . '/';
		$savePath = './uploads/' . $dir;
		$this->_mkDir($savePath);
		if (I ( 'get.site' ) || I ( 'get.category' )) {
			$fileName = I ( 'get.site' ) . I ( 'get.category' ) . '-';
		}
		$fileName .= uniqid ();
		$upload = new UploadFile (); // 实例化上传类
		$upload->maxSize = 1024 * 1024 * 2; // 设置附件上传大小
		$upload->allowExts = array (
				'jpg',
				'gif',
				'png',
				'jpeg' 
		);
		// 设置附件上传类型
		$upload->savePath = $savePath; // 设置附件上传目录
		$upload->uploadReplace = true;
		$upload->saveRule = $fileName;
		if (! $upload->upload ()) { // 上传错误提示错误信息
			$data ['msg'] = $upload->getErrorMsg ();
			$data ['status'] = false;
		} else { // 上传成功 获取上传文件信息
			$info = $upload->getUploadFileInfo ();
			$data ['name'] = $info[0]['name'];
			$path = $info [0] ['savepath'] . $info [0] ['savename'];
			$data ['status'] = true;
			// 上传到又拍云
			$data ['path'] = str_replace ( './uploads/', '/', $path );
			$upyun = new UpYun ( C ( 'upyun_bucket' ), C ( 'upyun_username' ), C ( 'upyun_password' ) );
			$fh = fopen ( $path, 'rb' );
			$rsp = $upyun->writeFile ( $data ['path'], $fh, True ); // 上传图片，自动创建目录
		}
		
		$this->ajaxReturn ( $data );
	}
}